package com.ioftv.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ioftv.dto.ImportResultDTO;
import com.ioftv.dto.ManagerPerformanceExcelDTO;
import com.ioftv.entity.ManagerPerformance;
import com.ioftv.service.ManagerPerformanceService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 项目经理绩效Excel导入监听器
 * 使用监听器模式处理大文件，避免内存溢出
 */
@Slf4j
public class ManagerPerformanceImportListener extends AnalysisEventListener<ManagerPerformanceExcelDTO> {

    /**
     * 每隔500条存储数据库，然后清理list，方便内存回收
     */
    private static final int BATCH_COUNT = 500;

    private List<ManagerPerformance> cachedDataList = new ArrayList<>(BATCH_COUNT);

    private ManagerPerformanceService managerPerformanceService;

    private ImportResultDTO importResult;
    
    private Long userId; // 用户ID，用于数据隔离

    private int currentRow = 1; // 当前行号（从1开始，不包括表头）

    public ManagerPerformanceImportListener(ManagerPerformanceService managerPerformanceService, ImportResultDTO importResult) {
        this.managerPerformanceService = managerPerformanceService;
        this.importResult = importResult;
    }
    
    /**
     * 设置用户ID
     * @param userId 用户ID
     */
    public void setUserId(Long userId) {
        this.userId = userId;
    }

    /**
     * 每解析一行数据都会调用此方法
     */
    @Override
    public void invoke(ManagerPerformanceExcelDTO data, AnalysisContext context) {
        currentRow++;
        importResult.setTotalRows(importResult.getTotalRows() + 1);

        try {
            // 数据校验
            String errorMsg = validateData(data);
            if (errorMsg != null) {
                importResult.addError(currentRow, errorMsg);
                return;
            }

            // 转换DTO为实体
            ManagerPerformance entity = convertToEntity(data);
            // 设置用户ID，实现数据隔离
            entity.setUserId(userId);
            cachedDataList.add(entity);

            // 达到BATCH_COUNT，批量保存一次
            if (cachedDataList.size() >= BATCH_COUNT) {
                saveData();
            }

        } catch (Exception e) {
            log.error("解析第{}行数据失败", currentRow, e);
            importResult.addError(currentRow, "数据解析失败: " + e.getMessage());
        }
    }

    /**
     * 所有数据解析完成后调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 保存剩余数据
        saveData();
        log.info("所有数据解析完成，共{}行，成功{}行，失败{}行", 
                importResult.getTotalRows(), 
                importResult.getSuccessRows(), 
                importResult.getFailRows());
    }

    /**
     * 批量保存数据
     */
    private void saveData() {
        if (cachedDataList.isEmpty()) {
            return;
        }

        try {
            boolean success = managerPerformanceService.saveBatch(cachedDataList);
            if (success) {
                int count = cachedDataList.size();
                for (int i = 0; i < count; i++) {
                    importResult.addSuccess();
                }
                log.info("批量保存{}条数据成功", count);
            } else {
                log.error("批量保存失败");
                for (int i = 0; i < cachedDataList.size(); i++) {
                    importResult.addError(currentRow - cachedDataList.size() + i + 1, "保存失败");
                }
            }
        } catch (Exception e) {
            log.error("批量保存数据失败", e);
            for (int i = 0; i < cachedDataList.size(); i++) {
                importResult.addError(currentRow - cachedDataList.size() + i + 1, "保存失败: " + e.getMessage());
            }
        } finally {
            cachedDataList.clear();
        }
    }

    /**
     * 数据校验
     */
    private String validateData(ManagerPerformanceExcelDTO data) {
        if (data.getManagerId() == null) {
            return "项目经理ID不能为空";
        }

        if (data.getManagerName() == null || data.getManagerName().trim().isEmpty()) {
            return "项目经理姓名不能为空";
        }

        if (data.getCompletedCount() == null || data.getCompletedCount() < 0) {
            return "完成数量不能为空或小于0";
        }

        if (data.getStatYear() == null) {
            return "统计年份不能为空";
        }

        if (data.getStatMonth() == null) {
            return "统计月份不能为空";
        }

        // 验证统计月份范围
        if (data.getStatMonth() < 1 || data.getStatMonth() > 12) {
            return "统计月份取值范围：1-12";
        }

        if (data.getRanking() != null && data.getRanking() <= 0) {
            return "排名必须大于0";
        }

        return null;
    }

    /**
     * 将DTO转换为实体
     */
    private ManagerPerformance convertToEntity(ManagerPerformanceExcelDTO dto) {
        ManagerPerformance entity = new ManagerPerformance();
        entity.setManagerId(dto.getManagerId());
        entity.setManagerName(dto.getManagerName());
        entity.setCompletedCount(dto.getCompletedCount());
        entity.setStatYear(dto.getStatYear());
        entity.setStatMonth(dto.getStatMonth());
        entity.setRanking(dto.getRanking());
        return entity;
    }
}